#ifndef TELNET_H
#define TELNET_H

//#include <Server.h>
#include <Ethernet.h>

#include "domino.h"

extern char bname[6];
extern byte hours;
extern byte minutes;

//! Telnet server instance
Server Telnet(23);

const int NTP_PACKET_SIZE= 48; // NTP time stamp is in the first 48 bytes of the message

byte packetBuffer[ NTP_PACKET_SIZE]; //buffer to hold incoming and outgoing packets 


void initTelnetServer(){
	Telnet.begin();
}

/// This function reads the command from a telnet port
bool readFromTelnetPort(char *instruction)
{
	byte b;
	byte i=0;
	Client client = Telnet.available();
	if (client) {
  //Serial.println("RE");
		while (client.available() > 0) {
			b = client.read();
			switch (b) {
			case -1:	// Null char
			case 0:	// Null char
			case 33:	// !
			case 34:	// "
			case 35:	// #
			case 39:	// '
			case 10:	// LF: No deberia suceder, salvo en consola emulada
				break;
			case 4:	// EOT
			case 64:	// '@'
			case 127:	// DEL
//				Serial.print("N:telnq=");
//				Serial.println(b, DEC);
				client.stop();	// Close connection
				break;
			case 13:	// Final de linea
				output = TELNET;
				//processInstruction(instruction);
				i = 0;
				Serial.print("D:req=");
				Serial.println(instruction);
				return true;
				break;
			default:
				if ((i < BUFFERSIZE)
				    && (b >= 32 && b <= 126)) {
					instruction[i] = b;
					i++;
					instruction[i] = 0;
				} else {
					i = 0;
//					Serial.print(b, DEC);
				}
			}
		}
		//client.stop();
	}
	return false;
}

void sendOpenDomoAnnouncement(){
	char msg[50];
	char ipbuff[6];
	byte remoteip[4];
	remoteip[0]=eeprom_get_byte(EMNETCFOFFSET+7);
	remoteip[1]=eeprom_get_byte(EMNETCFOFFSET+8);
	remoteip[2]=eeprom_get_byte(EMNETCFOFFSET+9);
	remoteip[3]=255;


	strlcpy(msg, "OPENDOMO DEVICE ", sizeof(msg));
	itoan(remoteip[0],ipbuff,4); ipbuff[3]='.'; ipbuff[4]=0;
	strlcat(msg,ipbuff,sizeof(msg));
	itoan(remoteip[1],ipbuff,4); ipbuff[3]='.'; ipbuff[4]=0;
	strlcat(msg,ipbuff,sizeof(msg));
	itoan(remoteip[2],ipbuff,4); ipbuff[3]='.'; ipbuff[4]=0;
	strlcat(msg,ipbuff,sizeof(msg));
	itoan(eeprom_get_byte(EMNETCFOFFSET+10),ipbuff,4); ipbuff[3]=' '; ipbuff[4]=0;
	strlcat(msg,ipbuff,sizeof(msg));
	strlcat(msg,bname,sizeof(msg));
	//Serial.println(msg);
	Udp.sendPacket(msg,remoteip,22537);
}

// send an NTP request to the time server at the given address 
byte sendNTPpacket(byte *address)
{
  // set all bytes in the buffer to 0
  memset(packetBuffer, 0, NTP_PACKET_SIZE); 
  // Initialize values needed to form NTP request
  // (see URL above for details on the packets)
  packetBuffer[0] = 0b11100011;   // LI, Version, Mode
  packetBuffer[1] = 0;     // Stratum, or type of clock
  packetBuffer[2] = 6;     // Polling Interval
  packetBuffer[3] = 0xEC;  // Peer Clock Precision
  // 8 bytes of zero for Root Delay & Root Dispersion
  packetBuffer[12]  = 49; 
  packetBuffer[13]  = 0x4E;
  packetBuffer[14]  = 49;
  packetBuffer[15]  = 52;

  // all NTP fields have been given values, now
  // you can send a packet requesting a timestamp: 		   
  Udp.sendPacket( packetBuffer,NTP_PACKET_SIZE,  address, 123); //NTP requests are to port 123
  return true;
}

boolean synchronizeNTP(byte *server)
{
   if (sendNTPpacket(server)){
     delay(1000);
     if ( Udp.available() ) {  
       Udp.readPacket(packetBuffer,NTP_PACKET_SIZE);  // read the packet into the buffer
       unsigned long highWord = word(packetBuffer[40], packetBuffer[41]);
       unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]);  
       // combine the four bytes (two words) into a long integer
       // this is NTP time (seconds since Jan 1 1900):
       unsigned long secsSince1900 = highWord << 16 | lowWord;       
       // Unix time starts on Jan 1 1970. In seconds, that's 2208988800:
       const unsigned long seventyYears = 2208988800UL;     
       // subtract seventy years:
       unsigned long epoch = secsSince1900 - seventyYears;  
       hours = (epoch  % 86400L) / 3600;
       minutes = (epoch  % 3600) / 60;
       //seconds = epoch %60;
       return true;
     } else {
       return false;
     }
   } else {
     return false;
   }
}


#endif
